package com.yra.controller.common;

import com.yra.util.NewBeeMallUtils;
import com.yra.util.Result;
import com.yra.util.ResultGenerator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @Author: yrq
 * @Date: Create in 14:24 2019/12/16
 */
@Controller
@RequestMapping("common")
public class UpdateController {
    public final static String FILE_UPLOAD_DIC="F:\\初版\\upload\\";

    @RequestMapping(value = "/upload/file",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Result> upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file")MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDirectory = new File(FILE_UPLOAD_DIC);
        File destFile = new File(FILE_UPLOAD_DIC + newFileName);
        try {
            if (!fileDirectory.exists()){
                if (!fileDirectory.mkdir()){
                    throw new IOException("文件夹创建失败，路径为"+fileDirectory);
                }
            }
            file.transferTo(destFile);
            Result resultSuccess = ResultGenerator.genSuccessResult();
            resultSuccess.setData(NewBeeMallUtils.getHost(new URI(request.getRequestURL() + "")) + "/upload/" + newFileName);
            return ResponseEntity.status(HttpStatus.OK).body(resultSuccess);
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResultGenerator.genFailResult("文件上传失败"));
        }

    }

}
